<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div>
  <h1>显示文件内容</h1>
  <input type="file" id="file-uploader" accept=".jpg, .jpeg, .png, .pdf" >
  <!--显示图像-->
  <div id="image-grid"></div>
  <!--为图像创建一个url,用这个url来显示-->
  <div id="image-url"></div>
  <!--显示图像大小-->
  <div id="feedback"></div>
  <!--显示上传进度-->
  <label id="progress-label" for="progress"></label>
  <progress id="progress" value="0" max="100"> </progress>
</div>
<script>
  const fileUploader = document.getElementById('file-uploader');
  const reader = new FileReader();
  const imageGrid = document.getElementById('image-grid');
  const progress = document.getElementById('progress');
  const imageGridURL = document.getElementById('image-url');


fileUploader.addEventListener('change', (event) => {
  const files = event.target.files;
  const file = files[0];
  const img = document.createElement('a');
  imageGridURL.appendChild(img);
  //创建唯一的url
  img.href = URL.createObjectURL(file);
  img.innerText = file.name;
  //img.alt = file.name;
  //获取文件大小
  const size = file.size;
  // 上传后获取文件对象并读取
  // 数据作为URL二进制字符串
  reader.readAsDataURL(file);
  //向用户传递的文件大小信息
  let msg = '';

 // 检查文件大小是否大于1MB，并准备一条消息。
  if (size > 1024 * 1024) {
      msg = `<span style="color:red;">The allowed file size is 1MB. The file you are trying to upload is of ${returnFileSize(size)}</span>`;
  } else {
      msg = `<span style="color:green;"> A ${returnFileSize(size)} file has been uploaded successfully. </span>`;
  }
// 加载后，对字符串进行处理
  reader.addEventListener('load', (event) => {
  // 在这里我们创建一个图像标签并添加图片
    const img = document.createElement('img');
    imageGrid.appendChild(img);
    img.src = event.target.result;
    img.alt = file.name;
  });
  //上传进度
  reader.addEventListener('progress', (event) => {
    if (event.loaded && event.total) {
      const percent = (event.loaded / event.total) * 100;
      progress.value = percent;
      document.getElementById('progress-label').innerHTML = Math.round(percent) + '%';

      if (percent === 100) {
        let msg = `<span style="color:green;">File <u><b>${file.name}</b></u> has been uploaded successfully.</span>`;
        feedback.innerHTML = msg;
      }
    }
  });
});
//返回图片大小的函数
  function returnFileSize(number) {
  if(number < 1024) {
    return number + 'bytes';
  } else if(number >= 1024 && number < 1048576) {
    return (number/1024).toFixed(2) + 'KB';
  } else if(number >= 1048576) {
    return (number/1048576).toFixed(2) + 'MB';
  }
}
</script>
</body>
</html>
